local modname = minetest.get_current_modname()
local S = minetest.get_translator(modname)

if not throwables then return end

local item_name = "default:torch"
local projectile_name = modname .. ':' .. item_name:match(".*:([^:]*)$") .. "_thrown"

if not minetest.registered_items[item_name] then return end

-- Add throwable capacity to default:snow
local torch = throwables:add(item_name, {
    projectile_name = projectile_name,
    initial_properties = {
        hp_max = 1,
        physical = true,
        collide_with_objects = true,
        collisionbox = {-0.2, -0.2, -0.2, 0.2, 0.2, 0.2},
        visual = "wielditem",
        visual_size = {x = 0.5, y = 0.5},
        textures = {"default:torch"},
        pointable = false,
        speed = 20,
        gravity = 9.8,
        lifetime = 5,
        damage = 2,
        glow = 14,
    },
})


-- Callback functions
function on_hit_entity(self, entity)
    entity:set_hp(entity:get_hp() - self.initial_properties.damage)
    self.object:remove()
end
function on_hit_player(self, player)
    on_hit_entity(self, player)
end

function on_hit_node(self, node, pos)
    local node_name
    local obj_pos = self.object:get_pos()
    local obj_rot = self.object:get_rotation()
    local obj_dir = { x = obj_rot.x, y = obj_rot.y, z = obj_rot.z }

    local raycast = minetest.raycast(obj_pos, pos, true, false)
    -- local raycast = minetest.raycast(pos, vector.add(pos, obj_dir), true, false)
    -- local raycast = minetest.raycast(vector.subtract(pos, obj_dir), pos, true, false)

    local pointed_thing = raycast:next()

    if pointed_thing and pointed_thing.type == "node" then
        local under = pointed_thing.under
        local above = pointed_thing.above
        local wdir = minetest.dir_to_wallmounted(vector.subtract(under, above))
        local player = minetest.get_player_by_name(self._player_name)

        if wdir < 0 then node_name = 'default:torch_ceiling'
        elseif wdir > 1 then node_name = 'default:torch_wall'
        else node_name = 'default:torch'
        end

        local itemstack, position = minetest.item_place(ItemStack({ name = node_name }), player, pointed_thing, wdir)

        print(dump(itemstack))
        if itemstack:is_empty() then
            self.object:remove()
            minetest.sound_play('default_place_node_hard', { pos = above, gain = 1.0, max_hear_distance = 10 })
            return
        end
    end


    local drop_pos = vector.subtract(obj_pos, vector.multiply(obj_dir, 0.1))
    local drop = minetest.add_item(obj_pos, ItemStack("default:torch"))
    if drop then
        drop:get_luaentity().velocity = vector.multiply(obj_dir, -1)
    end
end


-- Register callbacks
torch:on_hit_player(on_hit_player)
torch:on_hit_entity(on_hit_entity)
torch:on_hit_node(on_hit_node)
